<template>
  <div class="app-container">
    <el-collapse-transition>
      <el-form v-if="openCondition" :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
        <el-form-item label="请求标志" prop="lastReqId">
          <el-input
            v-model="queryParams.lastReqId"
            placeholder="请输入请求标志"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="配置名称" prop="configId">
          <el-select v-model="queryParams.configId" placeholder="请选择" filterable clearable size="small">
            <el-option
              v-for="dict in configOptions"
              :key="dict.id"
              :label="dict.configName"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="数据组" prop="groupName">
          <el-select v-model="queryParams.groupName" placeholder="请选择数据组" filterable allow-create default-first-option
                     clearable
                     size="small">
            <el-option
              v-for="dict in dataDropDownOptions"
              :key="dict.theName"
              :label="dict.theName"
              :value="dict.theName"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="响应结果" prop="rspResult">
          <el-select v-model="queryParams.rspResult" placeholder="请选择响应结果" clearable size="small">
            <el-option
              v-for="dict in rspResultOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="是否匹配" prop="matchPattern">
          <el-select v-model="queryParams.matchPattern" placeholder="请选择是否匹配" clearable size="small">
            <el-option
              v-for="dict in matchPatternOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </el-collapse-transition>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          size="mini"
          @click="handleExport"
        >导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          @click="handleDeleteGroup"
        >清除日志
        </el-button>
      </el-col>
      <el-col :span="1.5" style="float: right">
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button :type="!openCondition?'success':'info'"
                   :icon="!openCondition?'el-icon-caret-bottom':'el-icon-caret-top'" size="mini"
                   @click="openCondition=!openCondition">{{!openCondition?'展开条件':'收起条件'}}
        </el-button>
      </el-col>
    </el-row>

    <el-table :data="logList" height="580" @sort-change="handleSortChange"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <!--<el-table-column label="序号" width="50">
        <template scope="scope">
          <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
        </template>
      </el-table-column>-->
      <el-table-column label="请求标志" align="center" prop="lastReqId" width="200"/>
      <el-table-column label="配置名称" align="center" prop="configName"/>
      <el-table-column label="数据组" align="center" prop="groupName" width="250"/>
      <el-table-column label="号码" align="center" prop="groupData" width="120"/>
      <el-table-column label="开始时间" align="center" prop="startTime" width="170">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endTime" width="170">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="请求时长" align="center" sortable="custom" width="120" prop="reqTime"/>
      <el-table-column label="是否匹配" align="center" prop="matchPattern">
        <template slot-scope="scope">
          <el-tag size="medium">{{ scope.row.matchPattern.value }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="响应结果" align="center" prop="rspResult">
        <template slot-scope="scope">
          <el-tag size="medium">{{ scope.row.rspResult.value }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" width="180" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-info"
            @click="handleView(scope.row)"
          >详情
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:log:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改请求日志对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="750px">
      <!-- 修改 -->
      <el-form v-if="this.edit" ref="form" :model="form" :rules="rules" label-width="140px">
        <el-form-item label="请求配置ID" prop="configId">
          <el-input v-model="form.configId" placeholder="请输入请求配置ID"/>
        </el-form-item>
        <el-form-item label="url参数" prop="urlParam">
          <el-input v-model="form.urlParam" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="body参数" prop="bodyParam">
          <el-input v-model="form.bodyParam" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="header参数" prop="headerParam">
          <el-input v-model="form.headerParam" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker clearable size="small"
                          v-model="form.startTime"
                          type="date"
                          format="yyyy-MM-dd HH:mm:ss"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          placeholder="选择开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker clearable size="small"
                          v-model="form.endTime"
                          type="date"
                          format="yyyy-MM-dd HH:mm:ss"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          placeholder="选择结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="请求时长" prop="reqTime">
          <el-input v-model="form.reqTime" placeholder="请输入请求时长"/>
        </el-form-item>
        <el-form-item label="响应结果" prop="rspResult">
          <el-select v-model="form.rspResult" placeholder="请选择响应结果">
            <el-option
              v-for="dict in rspResultOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="是否匹配" prop="matchPattern">
          <el-select v-model="form.matchPattern" placeholder="请选择是否匹配">
            <el-option
              v-for="dict in matchPatternOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="响应内容" prop="rspBody">
          <el-input v-model="form.rspBody" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
      </el-form>
      <!-- 添加 -->
      <el-form v-if="!this.edit" ref="form" :model="form" :rules="rules" label-width="140px">
        <el-form-item label="请求配置ID" prop="configId">
          <el-input v-model="form.configId" placeholder="请输入请求配置ID"/>
        </el-form-item>
        <el-form-item label="url参数" prop="urlParam">
          <el-input v-model="form.urlParam" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="body参数" prop="bodyParam">
          <el-input v-model="form.bodyParam" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="header参数" prop="headerParam">
          <el-input v-model="form.headerParam" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker clearable size="small"
                          v-model="form.startTime"
                          type="date"
                          format="yyyy-MM-dd HH:mm:ss"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          placeholder="选择开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker clearable size="small"
                          v-model="form.endTime"
                          type="date"
                          format="yyyy-MM-dd HH:mm:ss"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          placeholder="选择结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="请求时长" prop="reqTime">
          <el-input v-model="form.reqTime" placeholder="请输入请求时长"/>
        </el-form-item>
        <el-form-item label="响应结果" prop="rspResult">
          <el-select v-model="form.rspResult" placeholder="请选择响应结果">
            <el-option
              v-for="dict in rspResultOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="是否匹配" prop="matchPattern">
          <el-select v-model="form.matchPattern" placeholder="请选择是否匹配">
            <el-option
              v-for="dict in matchPatternOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="响应内容" prop="rspBody">
          <el-input v-model="form.rspBody" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" size="mini">确 定</el-button>
        <el-button @click="cancel" size="mini">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 请求日志详情 -->
    <el-dialog title="请求日志详情" :visible.sync="viewOpen" width="750px">
      <el-form :inline="true" class="detail-inline" label-width="140px">
        <el-form-item label="配置名称：">
          <input class="bird-view-info-input" disabled :title="viewData.configName" :value="viewData.configName"/>
        </el-form-item>
        <el-form-item label="数据组：">
          <input class="bird-view-info-input" disabled :title="viewData.groupName" :value="viewData.groupName"/>
        </el-form-item>
        <el-form-item label="数据：">
          <input class="bird-view-info-input" disabled :title="viewData.groupData" :value="viewData.groupData"/>
        </el-form-item>
        <el-form-item label="请求URL：">
          <div style="color: #606266;width:700px;" v-html="viewData.theUrl"></div>
        </el-form-item>
        <el-form-item style="width: 100%;" label="url参数：">
          <div style="color: #606266;width:700px;" v-html="viewData.urlParam"></div>
        </el-form-item>
        <el-form-item style="width: 100%;" label="body参数：">
          <div style="color: #606266;width:700px;" v-html="viewData.bodyParam"></div>
        </el-form-item>
        <el-form-item style="width: 100%;" label="header参数：">
          <div style="color: #606266;width:700px;" v-html="viewData.headerParam"></div>
        </el-form-item>
        <el-form-item label="开始时间：">
          <input class="bird-view-info-input" disabled :title="viewData.startTime"
                 :value="viewData.startTime"/>
        </el-form-item>
        <el-form-item label="结束时间：">
          <input class="bird-view-info-input" disabled :title="viewData.endTime" :value="viewData.endTime"/>
        </el-form-item>
        <el-form-item label="请求时长：">
          <input class="bird-view-info-input" disabled :title="viewData.reqTime" :value="viewData.reqTime"/>
        </el-form-item>
        <el-form-item label="响应结果：">
          <input class="bird-view-info-input" disabled :title="viewData.rspResult"
                 :value="viewData.rspResult"/>
        </el-form-item>
        <el-form-item label="是否匹配：">
          <input class="bird-view-info-input" disabled :title="viewData.matchPattern"
                 :value="viewData.matchPattern"/>
        </el-form-item>
        <el-form-item style="width: 100%;" label="响应内容：">
          <div style="color: #606266;width:700px;">{{viewData.rspBody}}</div>
        </el-form-item>
        <el-form-item label="存储结果：">
          <div style="color: #606266;width:700px;" v-html="viewData.storeVal"></div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="viewOpen = false" size="mini">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {addLog, delLog, delLogData, getLog, listLog, updateLog} from "@/api/system/log";
  import {listConfig} from "@/api/system/apiConfig";
  import {dropDownData} from "@/api/system/data";
  import {download} from '@/utils/bird';
  import {getUserProfile} from "@/api/system/user";

  export default {
    data() {
      return {
        // 条件展开
        openCondition: true,
        // 是否修改
        edit: false,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        // 请求日志表格数据
        logList: [],
        // 弹出层标题
        title: "",
        // 是否显示详情弹出层
        viewOpen: false,
        // 是否显示弹出层
        open: false,
        // 响应结果字典
        rspResultOptions: [],
        configOptions: [],
        // 是否匹配字典
        matchPatternOptions: [],

        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          orderByColumn: 'id',
          isAsc: 'desc'
        },
        // 详情参数
        viewData: {},
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          configId: [
            {required: true, message: "请求配置ID不能为空", trigger: "blur"}
          ],
          startTime: [
            {required: true, message: "开始时间不能为空", trigger: "blur"}
          ],
          reqTime: [
            {required: true, message: "请求时长不能为空", trigger: "blur"}
          ],
          rspResult: [
            {required: true, message: "响应结果不能为空", trigger: "blur"}
          ],
          matchPattern: [
            {required: true, message: "是否匹配不能为空", trigger: "blur"}
          ],
          rspBody: [
            {required: true, message: "响应内容不能为空", trigger: "blur"}
          ]
        },
        dataDropDownOptions: [],
      };
    },
    created() {
      this.getList();
      this.getDicts("RspResultEnum").then(response => {
        this.rspResultOptions = response.data;
      });
      this.getDicts("FlagEnum").then(response => {
        this.matchPatternOptions = response.data;
      });
      const maxPageParams = {
        pageNum: 1,
        pageSize: 1000,
        orderByColumn: 'id',
        isAsc: 'desc'
      }
      listConfig(maxPageParams).then(response => {
        this.configOptions = response.data.list;
      });

      // 接口数据查询
      dropDownData().then(response => {
        this.dataDropDownOptions = response.data;
      });
    },
    methods: {
      /** 查询请求日志列表 */
      getList() {
        listLog(this.queryParams).then(response => {
          this.logList = response.data.list;
          this.total = response.data.total;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.resetPropField(this.form);
        this.clearForm('form');
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetPropField(this.queryParams, {pageNum: 1, pageSize: 10, orderByColumn: 'id', isAsc: 'desc'});
        this.handleQuery();
      },
      // 排序改变事件
      handleSortChange(sorter) {
        this.handleSort(this.queryParams, sorter);
        this.getList();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length != 1
        this.multiple = !selection.length
      },
      /** 详细按钮操作 */
      handleView(row) {
        const id = row.id
        getLog(id).then(response => {
          const {data} = response;
          console.log(response);
          this.viewData = {
            ...data,
            configId: data.configId && data.configId.name,
            rspResult: data.rspResult && data.rspResult.value,
            matchPattern: data.matchPattern && data.matchPattern.value,
          }
          this.viewOpen = true;
        });
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.edit = false;
        this.open = true;
        this.title = "添加请求日志";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.edit = true;
        this.reset();
        const id = row.id || this.ids
        getLog(id).then(response => {
          const {data} = response;
          this.form = {
            ...data,
            rspResult: data.rspResult && data.rspResult.key,
            matchPattern: data.matchPattern && data.matchPattern.key,
          }
          this.open = true;
          this.title = "修改请求日志";
        });
      },
      /** 提交按钮 */
      submitForm: function () {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != undefined) {
              updateLog(this.form).then(response => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addLog(this.form).then(response => {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$confirm('是否确认删除请求日志数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return delLog(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
      },
      handleExport() {
        const curQuery = this.queryParams;
        this.$confirm('确定要导出所选择的数据项?', "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          getUserProfile().then(response => {
            curQuery.userId = response.data.user.id;
            download("/system/reqLog/export", curQuery);
          });
        });
      },
      handleDeleteGroup() {
        this.$prompt('确定要清除所有请求日志?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          inputPattern: /\w+/,
          inputErrorMessage: '密码不能为空'
        }).then(function ({value}) {
          return delLogData(value);
        }).then(() => {
          this.getList();
          this.msgSuccess("清除成功");
        });
      },
    }
  };
</script>
